home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 5022 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.2 KB  |  76 lines

  1. Path: news.umbc.edu!not-for-mail
  2. From: schlein@umbc.edu (Jonas J. Schlein)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Question about sscanf
  5. Date: 10 Feb 1996 21:46:04 -0500
  6. Organization: University of Maryland Baltimore County
  7. Message-ID: <4fjl9c$51f@umbc9.umbc.edu>
  8. References: <4fe1oq$kuf@zippy.cais.net>
  9. NNTP-Posting-Host: umbc9.umbc.edu
  10. NNTP-Posting-User: schlein
  11.  
  12. USAID <usaid@cais.cais.com> wrote:
  13. |> Here is a fragment of code that I'm having a problem with.  The program 
  14. |> is bombing on the line containing the call to sscanf.  It assigns to the 
  15. |> first variable fine, but blows up on the second one.  I have no idea 
  16. |> what's wrong.
  17.  
  18. One thing you'll need is:
  19.  
  20. #include <stdio.h>
  21.  
  22. |> int formatFile(void)
  23. |> {
  24. |>    int i;
  25. |>    char line[MAX_LINE_LEN + 1]; 
  26.  
  27. MAX_LINE_LEN has not been defined anywhere in your program.
  28.  
  29. |>    char *name; 
  30. |>    char *value; 
  31. |>    char *val[MAXREGIONS]; 
  32.  
  33. Neither has MAXREGIONS.
  34.  
  35. |>    char *delimiter = ", "; 
  36. |>    FILE *ifp, *ofp; 
  37. |> 
  38. |>    /* open input and output files */
  39. |>    ifp = fopen("/opt/basis/tcs/formdata/test.txt", "r"); 
  40. |>    ofp = fopen("/opt/basis/tcs/formdata/import.txt", "w"); 
  41. |>    if ((ifp == NULL) || (ofp == NULL))
  42. |>       return (0); 
  43. |> 
  44. |>    while (fgetline(ifp, line, MAX_LINE_LEN) != -1)
  45.  
  46. In ANSI C there is no such function called fgetline(). I would change this
  47. to:
  48.  
  49.       while (fgets (line, MAX_LINE_LEN, ifp) != NULL)
  50. |>    {
  51. |>       /* store the name and value in variables */
  52. |>       if (sscanf(line, "%s %s", name, value) != 2)
  53.  
  54. Well there ya go! Expecting C to provide magic storage for variables
  55. will always get you in trouble. Pointers point to things that you
  56. make them point to. You have omitted this step and as such as writing
  57. to an undefined region of memory. To correct the problem you will need to
  58. either have a char array for these variables of appropriate length or
  59. dynamically allocate an acceptable block of memory before the sscanf() call.
  60. See the FAQ for information on scanf() related functions and malloc()
  61. usage.
  62.  
  63. |>       {
  64. |>          printf("Bad input from sscanf\n");
  65. |>          return (0); 
  66. |>       }
  67. |>         .
  68. |>         .
  69. |>         .
  70. |>     }
  71. |> }
  72. -- 
  73. "If it wasn't for C, we would be using BASI, PASAL, and OBOL."
  74.  
  75. Jonas J. Schlein  (schlein@gl.umbc.edu)
  76.